package com.example.demo;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@RestController
public class createPost {
    @PostMapping("/createPost")//url: 'http://localhost:8080/post/create'
    public ResponseEntity<Object> createPost(@RequestBody Map<String, String> requestBody) {
        //String postid="1234";
        //System.out.print("ok");
        Map<String, Object> data = new HashMap<>();
        //String posterid="1";

        String wxid= requestBody.get("postID");//用wxid得到usid
        String posterid=wxidgetuserid(wxid);
        String name = requestBody.get("name");
        String  location= requestBody.get("location");
        String  oldprice= requestBody.get("oldprice");
        String  newprice= requestBody.get("newprice");
        String  desc= requestBody.get("desc");







        Post post = new Post();
        post.setPosterId(posterid);
        post.setName(name);
        post.setLocation(location);
        post.setOldprice(oldprice);
        post.setNewprice(newprice);
        post.setDesc(desc);
        System.out.print(posterid+" "+name+" "+location+" "+oldprice+" "+newprice+" "+desc);

        // 保存到数据库
        //postRepository.save(post);
        int postid=insertDb(post);
        String piclaction="D:\\WeChat_Mini_Program\\BackEnd\\public\\post\\"+wxid+".png";
        File   file=new File(piclaction);   //指定文件名及路径
        String newname= String.valueOf(postid);
        file.renameTo(new File("D:\\WeChat_Mini_Program\\BackEnd\\public\\post\\"+newname+".png"));   //改名

        UpdateUserPub(posterid,postid);//参数用userid
        // 创建响应对象
        data.put("status", "COMPLETE");
        data.put("postid", postid);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return  new ResponseEntity<>(data, headers, HttpStatus.OK);
        //return ResponseEntity.ok("Post added successfully");
    }
    public static int insertDb (Post post){
        Connection con;

        try {
            //注册JDBC驱动程 序
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user = "root";
            String password = "gFL123456";
            Class.forName(driver);
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            //Statement stmt = con.createStatement();
            // 必须要写入id值，否则插入错误，建立数据库时，不是设置id值自动，为何还必须写入？？？
            //String sql = "insert into user values ('2020202020', '小米','20','2002.04.04','3','1233,1234')";
            String sql1 = "insert into post (posterid,name,location,oldprice,newprice,`time`)  values (?,?,?,?,?,?)";//,desc
            //String sql1 = "insert into posts values ("+post.id+","+post.name+","+post.oldprice+","+post.newprice+","+post.location+","+"'2','333','5678'"+","+post.name+","+post.desc+",'2')";
            //stmt.executeUpdate(sql);
            PreparedStatement preparedStatement = con.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
            //preparedStatement.setString(1, post.postid);
            preparedStatement.setString(1, post.posterid);
            preparedStatement.setString(2, post.name);
            preparedStatement.setString(3, post.location);
//                preparedStatement.setString(4, post.desc);
            preparedStatement.setString(4, post.oldprice);
            preparedStatement.setString(5, post.newprice);
            java.util.Date date = new java.util.Date();//获得当前时间
            Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型，这样便可以存入到Mysql数据库中
            preparedStatement.setTimestamp(6,t);
            System.out.println(new java.sql.Date(new java.util.Date().getTime()));

            // 执行插入操作
            int rowsAffected = preparedStatement.executeUpdate();

            int insertedId = 0;
            if (rowsAffected == 1) {
                // 获取插入记录的ID
                ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
                if (generatedKeys.next()) {
                    insertedId = generatedKeys.getInt(1);
                    System.out.println("Inserted ID: " + insertedId);
                }
            }
            //stmt.executeUpdate(sql1);
            preparedStatement.close();
            con.close();
            System.out.println("insert success!");
            UpdateDesc (post,insertedId);

            return insertedId;

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return 0;
    }
    public static void UpdateUserPub (String userid,int postid){
        Connection con;
        Map<String, Object> data = new HashMap<>();
        try {
            //注册JDBC驱动程 序
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user = "root";
            String password = "gFL123456";
            Class.forName(driver);
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            String sql = " select pub from user where userid=?;";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, userid);
            ResultSet rs = preparedStatement.executeQuery();
            String pub=null;
            if (rs.next()){
                pub = rs.getString("pub");
            }
            preparedStatement.close();
            String sql1 = "update user set `pub`=?  where userid=?;";
            PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
            if(pub==null){
                pub= String.valueOf(postid);
            }else pub=pub+","+postid;
            preparedStatement1.setString(1,pub);
            preparedStatement1.setString(2, userid);
            preparedStatement1.executeUpdate();
            preparedStatement1.close();
            con.close();
            System.out.println("insert desc success!");

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
    }
    public static void UpdateDesc (Post post,int insertedId){
        Connection con;
        Map<String, Object> data = new HashMap<>();
        try {
            //注册JDBC驱动程 序
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user = "root";
            String password = "gFL123456";
            Class.forName(driver);
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            String sql = "update post set `desc`=?,`like`=0,`dislike`=0  where postid=?;";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, post.desc);
            preparedStatement.setInt(2, insertedId);
            preparedStatement.executeUpdate();
            preparedStatement.close();
            con.close();
            System.out.println("insert desc success!");

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
    }
    public String wxidgetuserid(String wxid){
        Connection con;
        Map<String, Object> data = new HashMap<>();
        try {
            String driver="com.mysql.cj.jdbc.Driver";
            String url="jdbc:mysql://localhost:3306/jidazhidemai";

            // 数据库的用户名与密码，需要根据自己的设置
            String user="root";
            String password="gFL123456";
            Class.forName(driver);
            //注册JDBC驱动程 序
            //建立连接
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("数据库连接成功");
            }

            //Statement stmt = con.createStatement();
//            String sql = "INSERT INTO tab1 (title,author,submission_date) VALUES ('li','xiao','2020-07028')";
            String sql = " select userid from user where wxid=?;";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            preparedStatement.setString(1, wxid);
            ResultSet rs = preparedStatement.executeQuery();
            String userid="该用户未注册";
            if (rs.next()){
                userid = rs.getString("userid");
            }
            con.close();
            return userid;

        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动没有安装");

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return "false-出错了";
    }
}
